$(function () {
    function PMNeedPayBillItem() {
        this.billId = $('#billId').val();
        // 表格ID
        this.dataTable = $("#dataTable");
        this.viewForm = $('#bill-view-form');
        this.viewDiv = $('#bill-view-div');
        this.itemModal = $('#item-modal');
        // 按钮
        this.editBtn = $('#edit-btn');
        this.submitBtn = $('#submit-btn');
        this.saveItemBtn = $('#save-item-btn');
        this.addItemBtn = $('#add-item-btn');
        // 初始化
        this.init();
    }

    PMNeedPayBillItem.prototype.Constructor = PMNeedPayBillItem;

    PMNeedPayBillItem.prototype.init = function () {
        this.loadTable();
        this.registEvent();
    };

    PMNeedPayBillItem.prototype.loadTable = function () {
        var that = this;
        this.dataTable.dataTable({
            "sAjaxSource": "/pmbill/item/all",
            "aoColumns": [
                {"sWidth": "15%", "sTitle": "费用名称", "sClass": "center", "mData": "costName", "bSortable": false},
                {"sWidth": "15%", "sTitle": "起止日期", "sClass": "center", "mData": "duration", "bSortable": false},
                {"sWidth": "9%", "sTitle": "单价", "sClass": "center", "mData": "unitPrice", "bSortable": false},
                {"sWidth": "9%", "sTitle": "数量", "sClass": "center", "mData": "number", "bSortable": false},
                {"sWidth": "12%", "sTitle": "金额", "sClass": "center", "mData": "amount", "bSortable": false},
                {"sWidth": "12%", "sTitle": "创建时间", "sClass": "center", "mData": "created", "bSortable": false},
                {"sWidth": "14%", "sTitle": "备注", "sClass": "center", "mData": "remark", "bSortable": false},
                {"sWidth": "10%", "sTitle": "操作", "sClass": "center", "mData": "id", "bSortable": false}
            ],
            "aLengthMenu": [],
            "aaSorting": [],
            "bPaginate": false,
            "bInfo": false,
            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var id = aData["id"];
                if (aData['created']) {
                    $('td:eq(5)', nRow).html(SysTool.Date.formatDate(aData['created'], 'yyyy-MM-dd'));
                }
                // 操作
                var option = '<a title="编辑账单明细" billid="' + id + '" href="javascript:void(0)" class="btn btn-xs btn-info">编辑</a>';
                option += '&nbsp;<a title="删除账单明细" billid="' + id + '" href="javascript:void(0)" class="btn btn-xs btn-danger">删除</a>';
                $('td:eq(7)', nRow).html(option);
            },
            "fnServerParams": function (aoData) {
                aoData.push({name: "billId", value: that.billId});
            },
            "fnStateLoaded": function (oSettings, oData) {
//                alert(JSON.stringify(oData));
            }
        });
    };

    PMNeedPayBillItem.prototype.refreshTable = function () {
        this.dataTable.dataTable().fnClearTable();
    };

    PMNeedPayBillItem.prototype.registEvent = function () {
        var that = this;
        that.editBtn.click(function () {
            that.viewForm.removeClass('hide');
            that.viewDiv.addClass('hide');
        });

        that.submitBtn.click(function () {
            var houseNumber = $('#houseNumber').val();
            var userName = $('#userName').val();
            var userMobile = $('#userMobile').val();
            var totalAmount = $('#totalAmount').val();
            var releaseTime = $('#releaseTime').val();
            var remark = $('#remark').val();
            if (!userName || !(userName = userName.trim())) {
                BootBox.warning('住户姓名不能为空！');
                return false;
            }
            if (!userMobile || !(userMobile = userMobile.trim())) {
                BootBox.warning('手机号码不能为空！');
                return false;
            }
            if (userMobile && userMobile.length !== 11) {
                BootBox.warning('手机号码格式不正确！');
                return false;
            }
            if (!totalAmount || totalAmount <= 0) {
                BootBox.warning('金额不能为空且必须大于0！');
                return false;
            }
            if (!releaseTime) {
                BootBox.warning('出账日期不能为空！');
                return false;
            }
            SysTool.Ajax.ajaxSubmitForm('#bill-view-form', function (data) {
                $('#view-houseNumber').val(data.houseNumber);
                $('#view-userName').val(data.userName);
                $('#view-userMobile').val(data.userMobile);
                $('#view-duration').val(data.duration);
                $('#view-totalAmount').val(data.totalAmount);
                $('#view-releaseTime').val(SysTool.Date.formatDate(data.releaseTime, 'yyyy-MM-dd'));
                $('#view-remark').val(data.remark);
                that.viewForm.addClass('hide');
                that.viewDiv.removeClass('hide');
            });
        });

        that.dataTable.on('click', 'a.btn-danger', function () {
            var $that = $(this);
            BootBox.confirm('确定删除当前账单明细项？', function (b) {
                if (!b) return;
                var ids = $that.attr('billid');
                SysTool.Ajax.ajaxJsonCall('pmbill/item/delete/' + ids, {}, function (data) {
                    that.refreshTable();
                });
            });
        });
        // 编辑
        that.dataTable.on('click', 'a.btn-info', function () {
            var $that = $(this);
            var itemId = $that.attr('billid');
            SysTool.Ajax.ajaxJsonCall('pmbill/item/' + itemId, {}, function (data) {
                that.itemModal.find('.modal-header').text('编辑明细');
                that.itemModal.find('input:hidden').val(data.id);
                that.itemModal.find('#costName').val(data.costName);
                that.itemModal.find('#unitPrice').val(data.unitPrice);
                that.itemModal.find('#number').val(data.number);
                that.itemModal.find('#amount').val(data.amount);
                that.itemModal.find('#startDay').val(SysTool.Date.formatDate(data.startDay, 'yyyy-MM-dd'));
                that.itemModal.find('#endDay').val(SysTool.Date.formatDate(data.endDay, 'yyyy-MM-dd'));
                that.itemModal.find('#remark1').val(data.remark);
                that.itemModal.modal('show');
            });
        });
        // 添加
        that.addItemBtn.click(function () {
            that.itemModal.find('.modal-header').text('添加明细');
            that.itemModal.find('input:hidden').val('');
            that.itemModal.find('#costName').val('');
            that.itemModal.find('#unitPrice').val('');
            that.itemModal.find('#number').val('');
            that.itemModal.find('#amount').val('');
            that.itemModal.find('#startDay').val('');
            that.itemModal.find('#endDay').val('');
            that.itemModal.find('#remark1').val('');
            that.itemModal.modal('show');
        });
        // 保存费用明细
        that.saveItemBtn.click(function () {
            validateForm(function () {
                that.itemModal.modal('hide');
                that.refreshTable();
            });
        });

        function validateForm(callback) {
            if (!that.billId) {
                BootBox.warning('业务逻辑异常！');
                return false;
            }
            var id = that.itemModal.find('input:hidden').val();
            var costName = that.itemModal.find('#costName').val();
            var unitPrice = that.itemModal.find('#unitPrice').val();
            var number = that.itemModal.find('#number').val();
            var amount = that.itemModal.find('#amount').val();
            var startDay = that.itemModal.find('#startDay').val();
            var endDay = that.itemModal.find('#endDay').val();
            var remark = that.itemModal.find('#remark1').val();
            if (!costName || !costName.trim()) {
                BootBox.warning('费用名称不能为空！');
                return false;
            }
            if (unitPrice && unitPrice <= 0) {
                BootBox.warning('单价必须大于0！');
                return false;
            }
            if (number && number <= 0) {
                BootBox.warning('数量必须大于0！');
                return false;
            }
            if (!amount || amount <= 0) {
                BootBox.warning('金额不能为空且必须大于0！');
                return false;
            }
            if (!startDay) {
                BootBox.warning('开始日期不能为空！');
                return false;
            }
            if (!endDay || endDay <= 0) {
                BootBox.warning('结束日期不能为空！');
                return false;
            }
            costName = costName.trim();
            SysTool.Ajax.ajaxJsonCall('pmbill/item/save', {
                id: id,
                billId: that.billId,
                costName: costName,
                unitPrice: unitPrice,
                number: number,
                amount: amount,
                startDay: startDay,
                endDay: endDay,
                remark: remark
            }, function (data) {
                if (data) {
                    callback();
                } else {
                    BootBox.warning('保存失败，请稍后重试！');
                }
            })
        }

        $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
            //$(this).prev().focus();
        });

        SysTool.Html.bindEnterClick([], that.$seachr_btn);
    };

    window.PMNeedPayBillItem = new PMNeedPayBillItem();
});